package com.apes.scm.income.model;

import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.plugin.soe.annotations.State;
import com.apes.framework.plugin.soe.annotations.States;
import com.apes.framework.util.ApesConst;
import com.apes.scm.account.account.model.Cooperation;
import com.apes.scm.contract.model.Contract;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = Income.CONST_TABLE_NAME)
public class Income extends Model {
    public static final String CONST_TABLE_NAME = "pur_income";

    @Id
    @Column(name = "id", length = 32)
    @ApesGenerator(code = CONST_TABLE_NAME, name = "收入单", prefix = "P")
    @Comment("收入单号")
    private String id; //收入单号

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "contract_id", referencedColumnName = "id")
    @Comment("合同编码")
    private Contract contract; //合同号

    @Column(name = "source_business_type", length = 64)
    @Comment("来源单据类型")
    private String sourceBusinessType;

    @Column(name = "source_business_key", length = 64)
    @Comment("来源单据号码")
    private String sourceBusinessKey;

    @NotNull
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "company_id", referencedColumnName = "id")
    @Comment("公司编码")
    private PartyRole company; //公司

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "dept_id", referencedColumnName = "id", nullable = false)
    @Comment("部门编码")
    private Dept dept; //部门

    @NotNull
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "partner_id", referencedColumnName = "id", nullable = false)
    @Comment("业务伙伴编码")
    private PartyRole partner; //业务伙伴

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "cooperation_id", referencedColumnName = "id")
    @Comment("合作方式编码")
    private Cooperation cooperation; //合作方式

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "in_come_category", referencedColumnName = "id")
    @Comment("收入类别")
    private Enumeration inComeCategory;


    @Column(name = "fn_customer_expand_id", length = 128)
    @Comment("赋能客户车辆扩展信息")
    private String fnCustomerExpand;

    @Column(name = "CAR_LICENSE", length = 255)
    @Comment("车牌")
    private String carLicense;

    @Column(name = "amount", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("总计")
    private double amount = 0; //总计

    @States(name = "单据状态", values = {
            @State(id = "sent", name = "制单"),
            @State(id = "approve", name = "已审核")})
    @Column(name = "state", length = 10, nullable = false)
    private String state; //状态


    @Column(name = "note", length = 250)
    @Comment("备注")
    private String note; //备注

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "approve_uid", referencedColumnName = "id")
    @Comment("审核人")
    private PartyRole approveUID; //审核人

    @Column(name = "approve_date")
    @Comment("审核日期")
    private Date approveDate; //审核日期


    @Column(name = "origin", length = 30)
    @Comment("源单据")
    private String origin;

    @Column(name = "source", length = 30)
    @Comment("来源单据")
    private String source;

    @Column(name = "third_id", length = 30)
    @Comment("第三方单号")
    private String thirdId;

    @OneToMany(mappedBy = "income", cascade = CascadeType.ALL, orphanRemoval = true)
    private Set<IncomeItem> incomeItems = new HashSet(); //结算商品

    public Set<IncomeItem> getIncomeItems() {
        if (incomeItems == null) return new HashSet();
        for (IncomeItem item : incomeItems) {
            item.setIncome(this);
        }
        return incomeItems;
    }

    public void computeAmount() {
        amount = 0; // 先清空
        for (IncomeItem item : incomeItems) {
            amount += item.getIncomeAmount();
        }
    }

    @Transient
    private PartyRole _creator;

    @Transient
    public PartyRole get_creator() {
        if (this.getCreator() == null) return null;
        return SpringManager.getBean(PartyRoleRepository.class).findOne(this.getCreator());
    }

    /**
     * 检查是否全部扣收
     */
    public void checkDeduct() {
        long count = incomeItems.stream().filter(expenseItem -> expenseItem.getRecoveryAmount() == expenseItem.getIncomeAmount()).count();
        if (count == incomeItems.size()) {
            state = "approve";
        }
    }
}
